import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Typography,
  Drawer,
  message,
  Descriptions,
} from 'antd';
import {
  EyeOutlined,
  HistoryOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { scriptApi } from '@/services/api';
import type { Script, ScriptExecution } from '@/types';
import ExecutionResult from './ExecutionResult';

const { Title, Text } = Typography;

interface ExecutionHistoryProps {
  script: Script;
}

const ExecutionHistory: React.FC<ExecutionHistoryProps> = ({ script }) => {
  const [executions, setExecutions] = useState<ScriptExecution[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [executionDrawerVisible, setExecutionDrawerVisible] = useState(false);
  const [currentExecution, setCurrentExecution] = useState<ScriptExecution | null>(null);

  const fetchExecutions = async () => {
    setLoading(true);
    try {
      const response = await scriptApi.getScriptExecutions(script.id, {
        page: current,
        pageSize,
      });
      setExecutions(response.data?.data || []);
      setTotal(response.data?.total || 0);
    } catch (error) {
      message.error('获取执行历史失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchExecutions();
  }, [current, pageSize, script.id]);

  const handleViewExecution = (execution: ScriptExecution) => {
    setCurrentExecution(execution);
    setExecutionDrawerVisible(true);
  };

  const getStatusTag = (status: string) => {
    const statusMap = {
      running: { color: 'processing', text: '运行中' },
      completed: { color: 'success', text: '完成' },
      failed: { color: 'error', text: '失败' },
      cancelled: { color: 'warning', text: '已取消' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const formatDuration = (startTime: string, endTime?: string) => {
    const start = new Date(startTime);
    const end = endTime ? new Date(endTime) : new Date();
    const duration = Math.round((end.getTime() - start.getTime()) / 1000);
    
    if (duration < 60) {
      return `${duration}秒`;
    } else if (duration < 3600) {
      return `${Math.floor(duration / 60)}分${duration % 60}秒`;
    } else {
      const hours = Math.floor(duration / 3600);
      const minutes = Math.floor((duration % 3600) / 60);
      const seconds = duration % 60;
      return `${hours}时${minutes}分${seconds}秒`;
    }
  };

  const columns: ColumnsType<ScriptExecution> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '执行状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: getStatusTag,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 180,
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 180,
      render: (text) => text ? new Date(text).toLocaleString() : '-',
    },
    {
      title: '执行时长',
      key: 'duration',
      width: 120,
      render: (_, record) => formatDuration(record.startTime, record.endTime),
    },
    {
      title: '退出码',
      dataIndex: 'exitCode',
      key: 'exitCode',
      width: 80,
      render: (code) => code !== undefined ? code : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Button
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewExecution(record)}
        >
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Card
        title={
          <Space>
            <HistoryOutlined />
            <span>执行历史 - {script.name}</span>
          </Space>
        }
        extra={
          <Button
            icon={<ReloadOutlined />}
            onClick={fetchExecutions}
            loading={loading}
          >
            刷新
          </Button>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Descriptions column={2} size="small">
            <Descriptions.Item label="脚本名称">{script.name}</Descriptions.Item>
            <Descriptions.Item label="脚本类型">
              <Tag color={script.type === 'node' ? 'blue' : 'orange'}>
                {script.type === 'node' ? 'Node.js' : 'Python'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="脚本描述">
              {script.description || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={script.status === 'active' ? 'green' : 'red'}>
                {script.status === 'active' ? '启用' : '禁用'}
              </Tag>
            </Descriptions.Item>
          </Descriptions>
        </div>

        <Table
          columns={columns}
          dataSource={executions}
          loading={loading}
          scroll={{ x: 900 }}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条执行记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size!);
            },
          }}
          rowKey="id"
        />
      </Card>

      {/* 执行详情抽屉 */}
      <Drawer
        title="执行详情"
        placement="right"
        width={800}
        open={executionDrawerVisible}
        onClose={() => setExecutionDrawerVisible(false)}
      >
        {currentExecution && (
          <ExecutionResult execution={currentExecution} />
        )}
      </Drawer>
    </div>
  );
};

export default ExecutionHistory;